<template>
  <div class="article-manager">
    <!-- 搜索框、类型筛选、年份筛选和状态筛选 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="输入文章标题查询"
        @input="handleSearch"
        style="width: 250px"
      />
      
      <!-- 文章类型下拉框查询 -->
      <el-select
        v-model="selectedType"
        placeholder="选择文章类型"
        filterable
        clearable
        style="width: 200px; margin-left: 10px"
        @change="handleTypeChange"
      >
        <el-option
          v-for="type in allPossibleTypes"
          :key="type"
          :label="type"
          :value="type"
        />
      </el-select>
      
      <div class="filters-container">
        <div class="year-filters">
          <el-button
            v-for="(year, index) in years"
            :key="index"
            :class="{ 'active-filter': selectedYear === year }"
            @click="filterByYear(year)"
          >
            {{ year }}
          </el-button>
        </div>
        <div class="status-filters">
          <!-- 保留全部按钮 -->
          <el-button
            class="status-btn status-all"
            :class="{ 'active-filter': selectedStatus === 'all' }"
            @click="filterByStatus('all')"
          >
            全部
          </el-button>

          <!-- 其他状态按钮 -->
          <el-button
            v-for="(status, index) in statusOptions"
            :key="index"
            :class="['status-btn', `status-${status.value}`, { 'active-filter': selectedStatus === status.value }]"
            @click="filterByStatus(status.value)"
          >
            {{ status.label }}
          </el-button>
        </div>
      </div>
      <el-button type="success" @click="openNewArticleDialog" style="margin-left: 10px">新增文章</el-button>
    </div>

    <!-- 文章列表 -->
    <div class="article-list">
      <div
        class="article-card"
        v-for="article in filteredArticles"
        :key="article.id"
        @click="viewArticle(article)"
      >
        <!-- 封面展示区域 -->
        <div class="article-cover-container">
          <div class="cover-wrapper">
            <img 
              :src="getCoverUrl(article)" 
              alt="文章封面" 
              class="article-cover"
              :class="{ 'placeholder-cover': !hasCover(article) }"
              loading="lazy"
            >
            <div v-if="!hasCover(article)" class="cover-placeholder">
              <i class="el-icon-picture-outline"></i>
              <span>无封面图片</span>
            </div>
          </div>
          
          <!-- 文章类型标签和状态标签 -->
          <div class="article-tags-container">
            <div class="article-types-container">
              <span 
                class="article-type-badge" 
                v-for="(type, idx) in article.type" 
                :key="idx"
              >
                {{ type }}
              </span>
            </div>
            <div class="article-status-container">
              <span 
                class="article-status-badge" 
                :class="`status-${article.status}`"
              >
                {{ getStatusLabel(article.status) }}
              </span>
            </div>
          </div>
        </div>
        
        <div class="article-title">{{ article.title }}</div>
        <div class="article-meta">
          <span>{{ formatDate(article.createdAt) }}</span>
          <span v-if="article.updatedAt" class="updated-at">
            编辑于 {{ formatDate(article.updatedAt) }}
          </span>
        </div>
        <div class="article-actions">
          <el-button 
            type="primary" 
            @click.stop="openEditDialog(article)"
            :disabled="!canEditArticle(article)"
          >
            编辑
          </el-button>
          <el-button 
            type="danger" 
            @click.stop="confirmDelete(article)"
            :disabled="!canDeleteArticle(article)"
          >
            删除
          </el-button>
        </div>
      </div>
      
      <!-- 空状态处理 -->
      <div v-if="filteredArticles.length === 0" class="empty-state">
        <el-empty description="没有找到匹配的文章"></el-empty>
      </div>
    </div>

    <!-- 文章详情对话框 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      title="文章详情" 
      :width="detailDialogWidth"
      :before-close="handleDetailClose"
    >
      <div class="article-detail">
        <div class="detail-header">
          <h2 class="detail-title">{{ currentArticle.title }}</h2>
          <div class="detail-meta">
            <span class="publish-date">{{ formatDate(currentArticle.createdAt) }}</span>
            <span v-if="currentArticle.updatedAt" class="updated-at">
              编辑于 {{ formatDate(currentArticle.updatedAt) }}
            </span>
            <span class="detail-status">
              <span 
                class="status-badge" 
                :class="`status-${currentArticle.status}`"
              >
                {{ getStatusLabel(currentArticle.status) }}
              </span>
            </span>
          </div>
          <div class="detail-types">
            <el-tag v-for="(type, idx) in currentArticle.type" :key="idx" class="type-tag">
              {{ type }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-content">
          <p v-for="(paragraph, i) in contentParagraphs" :key="i">{{ paragraph }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 文章编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑文章" :width="editDialogWidth">
      <!-- 下线状态提示 -->
      <el-alert 
        v-if="isOfflineMode" 
        title="当前文章处于下线状态，仅可修改状态" 
        type="warning" 
        show-icon 
        style="margin-bottom: 15px"
      />
      
      <el-form :model="currentArticle" ref="articleForm">
        <!-- 文章标题 -->
        <el-input
          v-model="currentArticle.title"
          placeholder="请输入文章标题（最多100个字符）"
          maxlength="100"
          show-word-limit
          style="width: 100%; margin-bottom: 20px"
          :disabled="isOfflineMode"
        />

        <!-- 文章类型（多选）和状态选择 -->
        <div class="edit-form-row">
          <el-select
            v-model="currentArticle.type"
            placeholder="请选择文章类型"
            style="width: 65%; margin-right: 2%; margin-bottom: 20px"
            multiple
            filterable
            allow-create
            default-first-option
            :disabled="isOfflineMode"
          >
            <el-option label="计划" value="计划" />
            <el-option label="随笔" value="随笔" />
            <el-option label="HTML" value="HTML" />
            <el-option label="CSS" value="CSS" />
            <el-option label="JavaScript" value="JavaScript" />
            <el-option label="Vue" value="Vue" />
            <el-option label="React" value="React" />
            <el-option label="Node.js" value="Node.js" />
          </el-select>
          
          <!-- 状态选择器 -->
          <el-select
            v-model="currentArticle.status"
            placeholder="请选择状态"
            style="width: 33%; margin-bottom: 20px"
          >
            <el-option 
              v-for="status in statusOptions" 
              :key="status.value"
              :label="status.label" 
              :value="status.value"
            />
          </el-select>
        </div>

        <!-- 封面上传区域 -->
        <div class="cover-upload-section">
          <div class="cover-upload-header">
            <h3 class="cover-upload-title">封面设置</h3>
            <el-tooltip effect="dark" content="建议尺寸1200×675px（16:9），大小不超过5MB">
              <i class="el-icon-question-circle"></i>
            </el-tooltip>
          </div>
          
          <div class="cover-upload-content">
            <!-- 封面预览区 -->
            <div class="cover-preview-container">
              <div class="preview-wrapper" :class="{ 'no-preview': !hasCover(currentArticle) }">
                <el-skeleton 
                  v-if="coverPreviewLoading && hasCover(currentArticle)" 
                  active 
                  class="preview-skeleton"
                ></el-skeleton>
                
                <img 
                  v-else-if="hasCover(currentArticle)"
                  :src="getCoverUrl(currentArticle)" 
                  alt="封面预览" 
                  class="cover-preview"
                  @load="handleImageLoad"
                  @error="handleImageError"
                >
                <div v-else class="preview-placeholder">
                  <i class="el-icon-picture-outline" v-if="!isUploading"></i>
                  <i class="el-icon-loading" v-if="isUploading"></i>
                  <p>{{ isUploading ? '上传中...' : '未设置封面' }}</p>
                </div>
                
                <!-- 封面操作按钮组 -->
                <div class="cover-actions">
                  <el-button 
                    icon="el-icon-delete" 
                    size="mini" 
                    type="text" 
                    class="delete-cover"
                    @click.stop="removeCover"
                    v-if="hasCover(currentArticle)"
                    :disabled="isOfflineMode"
                  >
                    移除
                  </el-button>
                  <el-button 
                    icon="el-icon-refresh" 
                    size="mini" 
                    type="text" 
                    class="replace-cover"
                    @click.stop="triggerUpload"
                    :disabled="isOfflineMode"
                  >
                    {{ hasCover(currentArticle) ? '替换' : '上传' }}
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 上传区域 -->
            <div class="upload-area">
              <el-upload
                ref="coverUpload"
                class="cover-uploader"
                drag
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :on-error="handleUploadError"
                :on-progress="handleUploadProgress"
                :show-file-list="false"
                :http-request="customUpload"
                :disabled="isUploading || loading || isOfflineMode"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">点击或拖拽文件到此处上传</div>
                <div class="el-upload__tip">支持JPG、PNG格式，大小不超过5MB</div>
              </el-upload>
              
              <!-- 上传进度条 -->
              <el-progress 
                v-if="uploadProgress > 0 && uploadProgress < 100"
                :percentage="uploadProgress" 
                stroke-width="2"
                class="upload-progress"
              ></el-progress>
              
              <!-- 上传错误提示 -->
              <el-alert 
                v-if="uploadError" 
                :title="uploadError" 
                type="error" 
                show-icon 
                class="upload-error-alert"
                :closable="true"
                @close="uploadError = ''"
              />
            </div>
          </div>
        </div>

        <!-- 文章内容 -->
        <div class="article-content-section">
          <h3 class="content-title">文章内容</h3>
          <el-input
            v-model="currentArticle.content"
            type="textarea"
            placeholder="请输入文章内容..."
            :rows="12"
            style="width: 100%"
            :disabled="isOfflineMode"
          />
        </div>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="saveArticle" 
          :loading="loading"
        >
          保存文章
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      :width="'30%'"
      :before-close="handleDeleteClose"
    >
      <div class="delete-confirmation">
        <p>您确定要删除这篇文章吗？</p>
        <p class="article-title-to-delete">《{{ articleToDelete.title }}》</p>
        <p class="delete-warning">此操作不可撤销，删除后数据将永久丢失。</p>
      </div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="deleteArticle"
          :loading="deleting"
        >
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted } from 'vue';
import { ElMessage, ElNotification, ElSkeleton, ElEmpty, ElTag, ElButton, ElInput, ElSelect, ElOption, ElUpload, ElProgress, ElTooltip, ElDialog, ElAlert } from 'element-plus';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { storeToRefs } from 'pinia';

const components = {
  ElSkeleton,
  ElEmpty,
  ElTag,
  ElButton,
  ElInput,
  ElSelect,
  ElOption,
  ElUpload,
  ElProgress,
  ElTooltip,
  ElDialog,
  ElAlert
};

    const authStore = useAuthStore();
    const { isLoggedIn, user: currentUser } = storeToRefs(authStore);
    const router = useRouter();
    
    authStore.initAuth();
    
    const checkAuth = () => {
      if (!isLoggedIn.value) {
        ElMessage.warning('请先登录');
        router.push({
          path: '/login',
          query: { redirect: router.currentRoute.value.fullPath }
        });
        return false;
      }
      return true;
    };

    // 文章状态选项
    const statusOptions = [
      { label: '草稿', value: 'draft' },
      { label: '发布', value: 'published' },
      { label: '下线', value: 'offline' }
    ];

    // 文章数据 - 从localStorage加载
    const articles = ref(JSON.parse(localStorage.getItem('articles') || '[]'));

    // 状态管理
    const searchQuery = ref('');
    const selectedYear = ref('all');
    const selectedStatus = ref('all');
    const selectedType = ref(''); // 选中的文章类型
    const years = ref([ '2025', '2024', '2023', '2022', '2021', '2020', '2019']);
    const editDialogVisible = ref(false);
    const detailDialogVisible = ref(false);
    const deleteDialogVisible = ref(false);
    const detailDialogWidth = ref('70%');
    const editDialogWidth = ref('80%');
    
    // 初始化currentArticle为包含所有必要属性的响应式对象
    const currentArticle = ref({
      id: null,
      title: '',
      content: '',
      type: [],
      imageUrl: '',
      status: 'draft',
      createdAt: '',
      updatedAt: '',
      authorUsername: null
    });
    
    // 待删除的文章
    const articleToDelete = ref(null);
    const deleting = ref(false);
    const contentParagraphs = ref([]);
    const uploadError = ref('');
    
    // 封面相关状态
    const uploadProgress = ref(0);
    const coverPreviewLoading = ref(false);
    const detailCoverLoading = ref(false);
    const detailCoverHeight = ref('350px');
    const isUploading = ref(false);
    const loading = ref(false);

    // 判断是否为下线模式
    const isOfflineMode = computed(() => {
      return currentArticle.value.status === 'offline';
    });

    // 定义所有可能的文章类型（与编辑页面保持一致）
    const predefinedTypes = [
      '计划', 
      '随笔', 
      'HTML', 
      'CSS', 
      'JavaScript', 
      'Vue', 
      'React', 
      'Node.js'
    ];

    // 获取所有可能的文章类型（预定义类型 + 现有文章中创建的自定义类型）
    const allPossibleTypes = computed(() => {
      const typesSet = new Set(predefinedTypes);
      articles.value.forEach(article => {
        if (article.type && Array.isArray(article.type)) {
          article.type.forEach(type => {
            if (type) typesSet.add(type);
          });
        }
      });
      return Array.from(typesSet).sort();
    });

    // 筛选文章列表
    const filteredArticles = computed(() => {
      try {
        let filtered = articles.value || [];

        // 权限过滤
        filtered = filtered.filter(article => {
          if (!article || typeof article !== 'object') return false;
          
          if (!currentUser.value) {
            return article.status === 'published';
          }
          
          if (article.status === 'draft') {
            return article.authorUsername === currentUser.value.username;
          }
          
          if (article.status === 'offline') {
            return article.authorUsername === currentUser.value.username;
          }
          
          if (article.status === 'published') {
            return true;
          }
          
          return false;
        });

         // 按年份筛选 - 修改为正确处理'all'值
        if (selectedYear.value && selectedYear.value !== 'all') {
          filtered = filtered.filter(article => article?.createdAt?.includes(selectedYear.value));
        }

        // 按状态筛选 - 修改为正确处理'all'值
        if (selectedStatus.value && selectedStatus.value !== 'all') {
          filtered = filtered.filter(article => article?.status === selectedStatus.value);
        }

        // 按类型筛选
        if (selectedType.value) {
          filtered = filtered.filter(article => {
            return article.type && Array.isArray(article.type) && 
                   article.type.includes(selectedType.value);
          });
        }

        // 按标题搜索
        if (searchQuery.value) {
          filtered = filtered.filter(article =>
            article?.title?.toLowerCase().includes(searchQuery.value.toLowerCase())
          );
        }

        // 按时间降序排列
        return filtered.sort((a, b) => {
          const dateA = a.updatedAt ? new Date(a.updatedAt) : new Date(a.createdAt);
          const dateB = b.updatedAt ? new Date(b.updatedAt) : new Date(b.createdAt);
          return dateB - dateA;
        });
      } catch (error) {
        console.error('筛选文章出错:', error);
        return [];
      }
    });

    // 判断是否可以编辑文章
    const canEditArticle = (article) => {
      if (!currentUser.value) return false;
      return article.authorUsername === currentUser.value.username;
    };

    // 判断是否可以删除文章
    const canDeleteArticle = (article) => {
      if (!currentUser.value) return false;
      return article.authorUsername === currentUser.value.username;
    };

    // 监听当前文章内容变化
    watch(() => currentArticle.value.content, (newContent) => {
      if (newContent) {
        contentParagraphs.value = newContent.split('\n').filter(paragraph => paragraph.trim() !== '');
      } else {
        contentParagraphs.value = [];
      }
    });

    // 监听封面图片变化
    watch(() => currentArticle.value.imageUrl, (newUrl) => {
      if (newUrl) {
        coverPreviewLoading.value = true;
        nextTick(() => {
          coverPreviewLoading.value = false;
        });
      }
    });

    // 将图片文件转换为Base64格式
    const fileToBase64 = (file) => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    }

    // 自定义上传方法
    const customUpload = async (options) => {
      try {
        if (!checkAuth()) {
          options.onError(new Error('请先登录'));
          return;
        }

        isUploading.value = true;
        uploadError.value = '';
        coverPreviewLoading.value = true;
        
        // 模拟上传进度
        let progress = 0;
        const progressInterval = setInterval(() => {
          progress += 5;
          if (progress >= 95) progress = 95;
          options.onProgress({ percent: progress });
        }, 50);
        
        try {
          // 将图片转为Base64
          const base64Url = await fileToBase64(options.file);
          
          // 更新当前文章的封面
          currentArticle.value = {
            ...currentArticle.value,
            imageUrl: base64Url,
            imageFile: options.file
          };
          
          // 完成上传进度
          clearInterval(progressInterval);
          options.onProgress({ percent: 100 });
          
          // 通知成功
          options.onSuccess({ 
            success: true, 
            data: { url: base64Url } 
          });
          
          // 强制DOM更新以显示预览
          nextTick(() => {
            coverPreviewLoading.value = false;
          });
        } catch (error) {
          clearInterval(progressInterval);
          throw new Error('图片处理失败: ' + error.message);
        }
      } catch (error) {
        console.error('上传错误:', error);
        uploadError.value = error.message.includes('图片处理失败') 
          ? error.message 
          : '上传失败，请重试';
        options.onError(error);
      } finally {
        isUploading.value = false;
        uploadProgress.value = 0;
        coverPreviewLoading.value = false;
      }
    };

    // 处理上传成功
    const handleUploadSuccess = (response) => {
      if (response.success) {
        ElNotification.success({
          title: '成功',
          message: '封面上传成功',
          duration: 2000
        });
      } else {
        uploadError.value = response.message || '上传失败，请重试';
      }
    };

    // 处理上传失败
    const handleUploadError = () => {
      // 错误信息已在customUpload中设置
    };

    // 处理上传进度
    const handleUploadProgress = (event) => {
      uploadProgress.value = Math.floor(event.percent);
    };

    // 上传前检查
    const beforeUpload = (file) => {
      uploadError.value = '';
      
      // 检查文件类型
      const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJPGorPNG) {
        uploadError.value = '请上传JPG或PNG格式的图片';
        return false;
      }
      
      // 检查文件大小
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        uploadError.value = '图片大小不能超过5MB';
        return false;
      }
      
      return true;
    };

    // 手动触发上传
    const triggerUpload = () => {
      if (isUploading.value || loading.value || isOfflineMode.value) return;
      
      nextTick(() => {
        const uploadInput = document.querySelector('.cover-uploader input[type="file"]');
        if (uploadInput) {
          uploadInput.click();
        } else {
          uploadError.value = '上传组件初始化失败，请刷新页面重试';
        }
      });
    };

    // 移除封面
    const removeCover = () => {
      if (!checkAuth() || isOfflineMode.value) return;
      
      currentArticle.value = {
        ...currentArticle.value,
        imageUrl: '',
        imageFile: null
      };
      coverPreviewLoading.value = false;
      ElMessage.success('封面已移除');
    };

    // 保存文章
    const saveArticle = async () => {
      try {
        if (!checkAuth()) return;
        
        // 表单验证
        if (!currentArticle.value.title && !isOfflineMode.value) {
          ElMessage.error('请输入文章标题');
          return;
        }
        if (!currentArticle.value.type || currentArticle.value.type.length === 0) {
          ElMessage.error('请选择至少一个文章类型');
          return;
        }
        if (['published', 'offline'].includes(currentArticle.value.status) && 
            (!currentArticle.value.content || currentArticle.value.content.trim() === '')) {
          ElMessage.error('发布或下线状态的文章必须包含内容');
          return;
        }

        loading.value = true;
        
        try {
          // 获取当前日期
          const currentDate = new Date().toISOString().split('T')[0];
          
          // 确保文章对象结构完整
          const articleData = {
            title: currentArticle.value.title,
            content: currentArticle.value.content,
            type: currentArticle.value.type,
            imageUrl: currentArticle.value.imageUrl || '',
            status: currentArticle.value.status || 'draft',
            createdAt: currentArticle.value.createdAt || currentDate,
            updatedAt: currentDate,
            authorUsername: currentArticle.value.authorUsername || currentUser.value.username
          };
          
          const articleIndex = articles.value.findIndex(article => article.id === currentArticle.value.id);
          if (articleIndex !== -1) {
            // 更新现有文章
            articleData.id = currentArticle.value.id;
            articles.value[articleIndex] = articleData;
            
            // 状态变更通知
            if (articles.value[articleIndex].status !== articleData.status) {
              ElNotification.info({
                title: '状态变更',
                message: `文章状态已变更为${getStatusLabel(articleData.status)}`,
                duration: 2000
              });
            }
          } else {
            // 创建新文章
            articleData.id = Date.now();
            articles.value.unshift(articleData);
          }

          // 保存到localStorage
          try {
            localStorage.setItem('articles', JSON.stringify(articles.value));
            ElNotification.success({
              title: '成功',
              message: '文章保存成功',
              type: 'success'
            });
            editDialogVisible.value = false;
          } catch (e) {
            console.error('localStorage保存失败:', e);
            if (e.name === 'QuotaExceededError') {
              ElMessage.error('存储空间不足，无法保存文章，请清理浏览器数据后重试');
            } else {
              ElMessage.error('保存失败，请重试');
            }
          }
        } catch (error) {
          console.error('保存文章错误:', error);
          ElMessage.error('保存失败，请重试');
        } finally {
          loading.value = false;
        }
      } catch (error) {
        console.error('保存文章出错:', error);
        ElMessage.error('操作失败，请重试');
        loading.value = false;
      }
    };

    // 确认删除文章
    const confirmDelete = (article) => {
      if (!checkAuth() || !canDeleteArticle(article)) return;
      
      articleToDelete.value = { ...article };
      deleteDialogVisible.value = true;
    };

    // 执行删除操作
    const deleteArticle = async () => {
      try {
        if (!articleToDelete.value || !checkAuth() || !canDeleteArticle(articleToDelete.value)) return;
        
        deleting.value = true;
        
        // 查找文章索引
        const articleIndex = articles.value.findIndex(
          article => article.id === articleToDelete.value.id
        );
        
        if (articleIndex !== -1) {
          // 从数组中删除文章
          articles.value.splice(articleIndex, 1);
          
          // 更新localStorage
          try {
            localStorage.setItem('articles', JSON.stringify(articles.value));
            ElNotification.success({
              title: '成功',
              message: '文章已删除',
              duration: 2000
            });
            
            // 关闭删除对话框
            deleteDialogVisible.value = false;
            
            // 如果删除的是当前正在查看的文章，关闭详情对话框
            if (detailDialogVisible.value && 
                currentArticle.value.id === articleToDelete.value.id) {
              detailDialogVisible.value = false;
            }
          } catch (e) {
            console.error('删除失败:', e);
            ElMessage.error('删除失败，请重试');
          }
        } else {
          ElMessage.error('未找到该文章，无法删除');
        }
      } catch (error) {
        console.error('删除文章出错:', error);
        ElMessage.error('删除失败，请重试');
      } finally {
        deleting.value = false;
      }
    };

    // 关闭删除对话框
    const handleDeleteClose = () => {
      deleteDialogVisible.value = false;
      articleToDelete.value = null;
    };

    // 图片加载完成后调整显示
    const handleImageLoad = (e) => {
      const img = e.target;
      const container = img.parentElement;
      
      if (img.naturalWidth > container.clientWidth || img.naturalHeight > container.clientHeight) {
        img.style.objectFit = 'cover';
      } else {
        img.style.objectFit = 'contain';
      }
      
      coverPreviewLoading.value = false;
    };

    // 处理图片加载失败
    const handleImageError = () => {
      uploadError.value = '封面图片加载失败，请重新上传';
      console.error('封面加载失败，URL:', currentArticle.value.imageUrl);
      coverPreviewLoading.value = false;
    };

    // 搜索处理
    const handleSearch = () => {};
    
    // 年份筛选
    const filterByYear = (year) => {
      selectedYear.value = year // === '全部' ? 'all' : year;
    };
    
    // 状态筛选
    const filterByStatus = (status) => {
      selectedStatus.value = status //=== '全部' ? 'all' : status;
    };
    
    // 类型筛选处理
    const handleTypeChange = () => {
      // 选择类型后自动触发筛选
    };
    
    // 获取状态显示文本
    const getStatusLabel = (statusValue) => {
      const status = statusOptions.find(option => option.value === statusValue);
      return status ? status.label : '未知';
    };
    
    // 查看文章详情
    const viewArticle = (article) => {
      try {
        currentArticle.value = { ...article };
        detailCoverLoading.value = !!article.imageUrl;
        detailDialogVisible.value = true;
      } catch (error) {
        console.error('查看文章出错:', error);
        ElMessage.error('无法查看文章，请重试');
      }
    };
    
    // 关闭详情对话框
    const handleDetailClose = () => {
      detailDialogVisible.value = false;
    };
    
    // 打开编辑对话框
    const openEditDialog = (article) => {
      try {
        if (!checkAuth() || !canEditArticle(article)) return;
        
        currentArticle.value = { ...article };
        uploadProgress.value = 0;
        uploadError.value = '';
        coverPreviewLoading.value = !!article.imageUrl;
        editDialogVisible.value = true;
      } catch (error) {
        console.error('打开编辑对话框出错:', error);
        ElMessage.error('无法编辑文章，请重试');
      }
    };
    
    // 打开新增文章对话框
    const openNewArticleDialog = () => {
      try {
        if (!checkAuth()) return;
        
        const today = new Date();
        const formattedDate = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
        
        currentArticle.value = {
          id: null,
          title: '',
          content: '',
          type: [],
          imageUrl: '',
          status: 'draft',
          createdAt: formattedDate,
          updatedAt: '',
          authorUsername: currentUser.value.username
        };
        uploadProgress.value = 0;
        uploadError.value = '';
        coverPreviewLoading.value = false;
        editDialogVisible.value = true;
      } catch (error) {
        console.error('打开新增文章对话框出错:', error);
        ElMessage.error('无法创建新文章，请重试');
      }
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      try {
        const date = new Date(dateString);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
      } catch (error) {
        console.error('格式化日期出错:', error);
        return dateString;
      }
    };
    
    // 检查是否有封面
    const hasCover = (article) => {
      return article && article.imageUrl && article.imageUrl.trim() !== '';
    };
    
    // 获取封面URL
    const getCoverUrl = (article) => {
      if (hasCover(article)) {
        return article.imageUrl;
      }
      return '';
    };

    // 组件挂载时初始化
    onMounted(() => {
      console.log('文章管理组件已挂载');
      authStore.initAuth();
      
      // 为现有文章添加状态和作者信息
      const updatedArticles = articles.value.map(article => {
        const updated = { ...article };
        if (!updated.status) {
          updated.status = 'published';
        }
        if (!updated.authorUsername && currentUser.value) {
          updated.authorUsername = currentUser.value.username;
        }
        return updated;
      });
      
      if (JSON.stringify(updatedArticles) !== JSON.stringify(articles.value)) {
        articles.value = updatedArticles;
        localStorage.setItem('articles', JSON.stringify(articles.value));
      }
    });
</script>

<style scoped>
.article-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-top: 20px;
}

.empty-state {
  grid-column: 1 / -1;
  padding: 40px 0;
  text-align: center;
}

.article-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  background-color: #fff;
}

.article-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.article-cover-container {
  position: relative;
  width: 100%;
  height: 180px;
  overflow: hidden;
}

.cover-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.article-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease, filter 0.3s ease;
}

.article-cover.placeholder-cover {
  filter: grayscale(1);
}

.article-card:hover .article-cover {
  transform: scale(1.03);
}

.cover-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
}

.cover-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
}

/* 文章标签容器 */
.article-tags-container {
  position: absolute;
  top: 12px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 12px;
  box-sizing: border-box;
  z-index: 2;
}

.article-types-container {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  max-width: 70%;
}

.article-type-badge {
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 12px;
  backdrop-filter: blur(4px);
  transition: background-color 0.3s ease;
}

.article-card:hover .article-type-badge {
  background: rgba(0, 0, 0, 0.8);
}

.article-status-container {
  display: flex;
  gap: 6px;
}

/* 状态标签样式 */
.article-status-badge {
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  backdrop-filter: blur(4px);
  color: white;
}

/* 不同状态的颜色 */
.status-draft {
  background-color: rgba(153, 153, 153, 0.8);
}

.status-published {
  background-color: rgba(72, 187, 120, 0.8);
}

.status-offline {
  background-color: rgba(237, 100, 166, 0.8);
}

.article-title {
  font-size: 16px;
  font-weight: 500;
  margin: 16px 12px 8px;
  padding: 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  color: #888;
  font-size: 12px;
  padding: 0 20px 12px;
}

.updated-at {
  color: #666;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
  width: 100%;
}

.filters-container {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.year-filters, .status-filters {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.status-btn {
  border-radius: 16px;
  padding: 5px 15px;
}

.active-filter {
  background-color: #409eff !important;
  color: white !important;
}

.article-actions {
  position: absolute;
  bottom: 12px;
  right: 12px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 3;
}

.article-card:hover .article-actions {
  opacity: 1;
}

/* 禁用状态的按钮样式 */
.article-actions .el-button.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.article-detail {
  padding: 10px 0;
}

.detail-header {
  margin-bottom: 24px;
}

.detail-title {
  font-size: 24px;
  margin-bottom: 16px;
  line-height: 1.5;
  font-weight: 600;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
  align-items: center;
}

.detail-status {
  display: flex;
  align-items: center;
}

.status-badge {
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.detail-types {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 24px;
}

.type-tag {
  background-color: #f0f2f5;
}

.detail-content {
  line-height: 1.8;
  font-size: 16px;
  color: #333;
}

.detail-content p {
  margin-bottom: 16px;
  white-space: pre-line;
}

.cover-upload-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
}

.cover-upload-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.cover-upload-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  margin-right: 10px;
}

.cover-upload-content {
  display: flex;
  gap: 20px;
  align-items: center;
}

@media (max-width: 768px) {
  .cover-upload-content {
    flex-direction: column;
  }
}

.cover-preview-container {
  flex: 1;
  min-width: 240px;
}

.preview-wrapper {
  position: relative;
  width: 100%;
  height: 160px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed #ddd;
}

.preview-wrapper.no-preview {
  background-color: #f5f5f5;
}

.cover-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.preview-placeholder i {
  font-size: 36px;
  margin-bottom: 8px;
}

.preview-placeholder p {
  margin: 0;
  font-size: 14px;
}

.cover-actions {
  position: absolute;
  bottom: 0;
  right: 0;
  display: flex;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 4px 0 0 0;
}

.cover-actions .el-button {
  color: #fff;
  margin: 0;
  padding: 4px 8px;
}

.cover-actions .el-button:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.cover-actions .el-button.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.delete-cover {
  border-right: 1px solid rgba(255, 255, 255, 0.2);
}

.upload-area {
  flex: 1;
  min-width: 240px;
  position: relative;
}

.cover-uploader {
  border: 1px dashed #ccc;
  border-radius: 6px;
  padding: 30px 20px;
  text-align: center;
  transition: border-color 0.3s ease;
}

.cover-uploader:hover:not(.is-disabled) {
  border-color: #409eff;
}

.cover-uploader.is-disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.upload-progress {
  margin-top: 12px;
  height: 6px;
}

.upload-error-alert {
  margin-top: 10px;
  padding: 6px 12px;
  font-size: 13px;
  width: 100%;
}

.article-content-section {
  margin-top: 20px;
}

.content-title {
  font-size: 16px;
  font-weight: 500;
  margin: 0 0 12px 0;
}

.edit-form-row {
  display: flex;
  gap: 10px;
}

/* 删除确认对话框样式 */
.delete-confirmation {
  padding: 10px 0;
}

.article-title-to-delete {
  color: #333;
  font-weight: 500;
  margin: 10px 0;
  padding-left: 10px;
  border-left: 3px solid #f56c6c;
}

.delete-warning {
  color: #f56c6c;
  font-size: 13px;
  margin-top: 15px;
}

@media (max-width: 768px) {
  .detail-dialog-width {
    width: 95% !important;
  }
  
  .edit-dialog-width {
    width: 95% !important;
  }
  
  .detail-title {
    font-size: 20px;
  }
  
  .edit-form-row {
    flex-direction: column;
  }
  
  .el-select {
    width: 100% !important;
    margin-right: 0 !important;
  }
  
  .article-actions {
    flex-direction: column;
    bottom: 8px;
    right: 8px;
  }
  
  .article-actions .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }
}
</style>